﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NPOI.SS.UserModel;

namespace Bamboo.Excel
{
    /// <summary>
    /// 逐字段、逐行写入sheet页的工具类
    /// </summary>
    public class SheetWriter
    {
        IWorkbook _workbook = null;
        ISheet _sheet = null;
        int _rowNo = 0;
        IRow _row = null;
        /// <summary>
        /// 变更工作簿，会重置所有状态
        /// </summary>
        /// <param name="workbook"></param>
        public void SetWorkbook(IWorkbook workbook)
        {
            if (_workbook == workbook) return;
            _workbook = workbook;
            _sheet = null;
            _rowNo = 0;
            _row = null;
        }
        /// <summary>
        /// 新建sheet页，并创建第0行。
        /// 如果之前未指定workbook则会先创建。
        /// </summary>
        /// <param name="sheetName"></param>
        public void AddSheet(string sheetName)
        {
            if (_workbook == null)
            {
                _workbook = new NPOI.XSSF.UserModel.XSSFWorkbook();
            }
            _sheet = _workbook.CreateSheet(sheetName);
            _rowNo = 0;
            _row = _sheet.CreateRow(0);
        }
        /// <summary>
        /// 批量设置列宽，单位：字符
        /// </summary>
        /// <param name="widthArray"></param>
        public void SetColumnWidths(params int[] widthArray)
        {
            for (int i = 0; i < widthArray.Length; ++i)
            {
                _sheet.SetColumnsWidth(widthArray);
            }
        }
        /// <summary>
        /// 批量增加单元格
        /// </summary>
        /// <param name="valueArray"></param>
        public void AddCells(params string[] valueArray)
        {
            for (int i = 0; i < valueArray.Length; ++i)
            {
                AddCell(i, valueArray[i]);
            }
        }
        
        public void AddCell(int index, string value)
        {
            var cell = _row.CreateCell(index, CellType.String);
            cell.SetCellValue(value);
        }

        public void AddCell(int index, double value)
        {
            var cell = _row.CreateCell(index, CellType.Numeric);
            cell.SetCellValue(value);
        }

        public void AddCell(int index, int value)
        {
            var cell = _row.CreateCell(index, CellType.Numeric);
            cell.SetCellValue(value);
        }

        public void NextRow()
        {
            _row = _sheet.AddRow(++_rowNo);
        }
        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="filename"></param>
        public void Save(string filename)
        {
            using (var fs = System.IO.File.OpenWrite(filename))
            {
                _workbook.Write(fs);
                fs.Close();
            }
        }
    }
}
